package com.base.common.beans;

import com.base.common.enums.ResultCodeEnum;

/**
 * 接口统一的返回结果
 *
 * @author Pengyan
 * @date 2018/8/14 16:28
 **/
public class Result<T> {

    /**
     * 状态码
     */
    private int code = ResultCodeEnum.SUCCESS.getCode();
    /**
     * 消息
     */
    private String msg;
    /**
     * 数据
     */
    private T data;

    public static <T> Result<T> from(Result<T> result) {
        if(null == result) {
            throw new RuntimeException("系统错误:非法的操作结果");
        }
        return build(ResultCodeEnum.getResultCode(result.getCode()), result.getMsg(), result.getData());
    }

    public static <T> Result<T> success() {
        return build(ResultCodeEnum.SUCCESS, "success", null);
    }

    public static <T> Result<T> success(T data) {
        return build(ResultCodeEnum.SUCCESS, "success", data);
    }

    public static <T> Result<T> success(String message) {
        return build(ResultCodeEnum.SUCCESS, message, null);
    }

    public static <T> Result<T> success(String message, T content) {
        return build(ResultCodeEnum.SUCCESS, message, content);
    }

    public static <T> Result<T> failure() {
        return build(ResultCodeEnum.FAILURE, null, null);
    }

    public static <T> Result<T> failure(String message) {
        return build(ResultCodeEnum.FAILURE, message, null);
    }

    public static <T> Result<T> failure(String message, T content) {
        return build(ResultCodeEnum.FAILURE, message, content);
    }

    /**
     * 业务异常
     * @param message
     * @param <T>
     * @return
     */
    public static <T> Result<T> businessWarn(String message) {
        return build(ResultCodeEnum.BUSINESS_WARN, message, null);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static <T> Result<T> build(ResultCodeEnum code, String message, T data) {
        Result ajax = new Result();
        ajax.setMsg(message);
        ajax.setCode(code.getCode());
        ajax.setData(data);
        return ajax;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    /**
     * 检验返回结果是否成功
     * @return
     */
    public static boolean isSuccessful(Result result) {
        return result != null && result.code == ResultCodeEnum.SUCCESS.getCode();
    }

    /**
     * 检验返回结果是否失败
     * @return
     */
    public static boolean isFailed(Result result) {
        return result == null || result.code != ResultCodeEnum.SUCCESS.getCode();
    }
}
